//
//  JXPublishViewController.swift
//  swift高仿微博
//
//  Created by peijiaxing on 16/3/6.
//  Copyright © 2016年 peijiaxing. All rights reserved.
//

import UIKit
import SnapKit

let holderString = "下雨天和巧克力更配........"

class JXPublishViewController: UIViewController , UITextViewDelegate ,UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    //定义一个成员变量来记录 底部toolBar的约束
    var bottomConstrant: Constraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNav()
        setupTextView()
        setupToolBar()
        
        // 添加通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

    
    // 设置 NAV 
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        let titleLabel = UILabel(frame: CGRectMake(0,0,200,44))
        
        titleLabel.numberOfLines = 0
        
        titleLabel.textAlignment = .Center
        
        let str = "发布微博\n\(JXUserViewModel.shareInstance.model?.screen_name ?? "")"
        // NSAttributedString -- 这个是不可变的,我们要修改属性的话,需要用到
        //NSMutableAttributedString
        let attribute = NSMutableAttributedString(string: str)
        
        // 改变 头的颜色
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15),NSForegroundColorAttributeName:UIColor.orangeColor()], range: NSMakeRange(4, str.characters.count - 4))
        
        titleLabel.attributedText = attribute
        
        navigationItem.titleView = titleLabel
    }
    
    @objc func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    @objc func publish(){
        
    }

    private func setupTextView(){
        
        // 添加视图
        view.addSubview(textView)
        textView.addSubview(photoView)
        
        
        // 设置约束
        textView.frame = view.frame
        
        textView.holderString = holderString
        
        textView.font = UIFont.systemFontOfSize(15)
        
        //实现代理方法
        textView.delegate = self
        
        //滑动 textView 让键盘消失
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
        
        
        // 设置 collectionView 约束
        photoView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(textView.snp_center)
            make.width.equalTo(UIScreen.mainScreen().bounds.size.width - 2*JXPhotoViewMargin)
            make.height.equalTo(UIScreen.mainScreen().bounds.size.width - 2*JXPhotoViewMargin)
            
        }
        
        
    }
    
    
    
    // MARK: --- 设置底部ToolBar
    
    private func setupToolBar(){
        toolBar.backgroundColor = UIColor.lightGrayColor()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        // 定义一个 数组 来接收 items
        var items = [UIBarButtonItem]()
        
        for setting in itemSettings{
            // 自定义按钮
            let button = UIButton(type: UIButtonType.Custom)
            
            // 设置按钮的属性
            button.setImage(UIImage(named: setting["imageName"]!), forState: UIControlState.Normal)
             // 高亮状态
            let imgName = setting["imageName"]!
            
            button.setImage(UIImage(named: "\(imgName)_highlighted"), forState: UIControlState.Highlighted)
            
            button.sizeToFit()
            
            if let action = setting["action"]{
                
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
                let item = UIBarButtonItem(customView: button)
                
                items.append(item)
                
                // 添加弹簧
                items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil))
        }
        
            // 把多出来的最后一个移除
            items.removeLast()
            
            toolBar.items = items
            // 添加视图并设置约束
            view.addSubview(toolBar)
            
            toolBar.snp_makeConstraints(closure: { (make) -> Void in
                make.left.equalTo(view.snp_left)
                make.right.equalTo(view.snp_right)
               self.bottomConstrant = make.bottom.equalTo(view.snp_bottom).constraint
                
                make.height.equalTo(40)
            })
            
        }
    
    //MARK:--选择图片的方法
    @objc private func choosePicture(){
        printLog("显示图片")
        
        // 判断手机能否显示相册
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            
            // 如果方法可以 就进行页面跳转
            let picker = UIImagePickerController()
            
            picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            
            picker.delegate = self
            
            presentViewController(picker, animated: true, completion: { () -> Void in
                
            })
        }
        
        
    }
    //MARK:--显示表情
    @objc private func inputEmoticon(){
        printLog("显示表情")
        
        textView.resignFirstResponder()
        
        if textView.inputView == nil {
            //
            textView.inputView = emoticonView
        } else {
            textView.inputView = nil
        }
        
        textView.becomeFirstResponder()

    }
    
    
    
    //MARK:--键盘改变的通知
    func changeToolBarFrame(noti: NSNotification){
        if let info = noti.userInfo{
            
            // 需要把 NSRect 转换成CGRect .
            let endFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            
            if endFrame?.origin.y == UIScreen.mainScreen().bounds.height {
                printLog("退出的时候")
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    self.bottomConstrant = make.bottom.equalTo(view.snp_bottom).constraint
                })
                
            } else {
                printLog("弹出的时候")
                
                toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    // 一定要注意可选项的问题
                    self.bottomConstrant = make.bottom.equalTo(view.snp_bottom).offset(-endFrame!.size.height).constraint
                })
            }
            
            //添加动画
            let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
            UIView.animateWithDuration(duration, animations: { () -> Void in
                
                //更新约束动画
                self.toolBar.layoutIfNeeded()
                
            })
            
        }
        
    }
    
    //MARK：--  移除通知
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    //MARK:--懒加载
    
    private lazy var textView: JXTextView = JXTextView()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var photoView: JXPhotoView = {
        
       let photo = JXPhotoView()
        
        weak var weakself = self
        
        photo.closure = {[unowned self] () -> () in
            
            weakself?.choosePicture()
        }
       
        return photo
    }()
    
    private lazy var emoticonView: JXEmoticonView = {
       
        let emoticon = JXEmoticonView()
        
        //颜色
        emoticon.backgroundColor = UIColor.yellowColor()
        
        emoticon.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 216)
        
        return emoticon
        
    }()
}

extension JXPublishViewController{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // 添加图片选择器
        
        photoView.addImages(image)
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        print("消失")
        
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
}


extension JXPublishViewController{
    
    func textViewDidChange(textView: UITextView) {
        
        //
        if textView.hasText() {
            // 不显示占位符
            self.textView.holderString = ""
            
            
        } else {
            // 显示占位符
            self.textView.holderString = holderString
        }
        
        //重绘
        self.textView.setNeedsDisplay()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
    }
    
}
